package com.kws.merchant.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kws.common.core.domain.R;
import com.kws.common.core.exception.ServiceException;
import com.kws.common.security.auth.AuthUtil;
import com.kws.merchant.domain.ContractTemplate;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.merchant.domain.po.ContentPo;
import com.kws.merchant.domain.po.ContractTemplatePo;
import com.kws.merchant.service.MerchantService;
import com.kws.merchant.util.FileUtil;
import com.kws.system.api.RemoteToolService;
import com.kws.system.api.domain.*;
import com.kws.merchant.mapper.ContractTemplateMapper;
import com.kws.merchant.service.ContractTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.web.multipart.MultipartFile;

/**
 * 合同管理-模板(ContractTemplate)表服务实现类
 *
 * @author yxy
 * @since 2024-10-29 15:37:33
 */
@Service("contractTemplateService")
public class ContractTemplateServiceImpl extends ServiceImpl<ContractTemplateMapper, ContractTemplate> implements ContractTemplateService {

    @Resource
    private ContractTemplateMapper contractTemplateMapper;
    @Autowired
    private RemoteToolService remoteToolService;
    @Autowired
    private MerchantService merchantService;
//    private static String eSignHost= EsignDemoConfig.EsignHost;
//    private static String eSignAppId=EsignDemoConfig.EsignAppId;
//    private static String eSignAppSecret=EsignDemoConfig.EsignAppSecret;


    /**
     * 分页查询列表
     */
    @Override
    public Page<ContractTemplate> pageList(ContractTemplatePo contractTemplatePo) {
        Page<ContractTemplate> page = new Page<>(contractTemplatePo.getPageSize(), contractTemplatePo.getTotalPage());
        LambdaQueryWrapper<ContractTemplate> queryWrapper = Wrappers.lambdaQuery();
        String name = contractTemplatePo.getName();//合同名称
        String type = contractTemplatePo.getType();//合同类型
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.eq(ContractTemplate::getName, name);
        }
        if (StringUtils.isNotEmpty(type)) {
            queryWrapper.eq(ContractTemplate::getType, type);
        }
        return this.page(page, queryWrapper);
    }

    /**
     * 修改合同
     *
     * @param contractTemplate
     * @return
     */
    @Override
    public Object updateContract(ContractTemplate contractTemplate) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        contractTemplate.setUpdateUser(sysUser.getUserId());
        return this.updateById(contractTemplate);
    }

    /**
     * 新增合同内容-用于测试
     *
     * @return
     */
    @Override
    public Object addContent(ContentPo contentPo) {
        ContractTemplate contractTemplate = this.getById(contentPo.getId());
        JSONObject content = contentPo.getContent();
//        contractTemplate.setContent(content.toJSONString());
        return this.updateById(contractTemplate);
    }

    /**
     * 新增合同模板
     *
     * @param templatePo
     * @return
     */
    @Override
    public Object addTemplate(TemplatePo templatePo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();

        MultipartFile file = templatePo.getFile();
        String name = templatePo.getName();
        Integer type = templatePo.getType();
        String templateType = templatePo.getTemplateType();
        ContractTemplate template = this.getType(type);
        if (ObjectUtils.isNotEmpty(template)){
            throw new RuntimeException("该类型合同模板已上传");
        }

        String fileNamw = merchantService.uploadCompanyFile(file);
        R<EQBTemplateVo> R = remoteToolService.saveContract(file);
        if (R.FAIL == R.getCode()) {
            throw new ServiceException(R.getMsg());
        }
        EQBTemplateVo eqbTemplateVo = R.getData();
        //{"code":0,"message":"成功","data":{"fileId":"66b61f0e9daa459495062a2869c593c0","fileName":"接入时发现的问题.docx","fileSize":null,
        // "fileStatus":2,"fileDownloadUrl":"https://esignoss.esign.cn/1111564182/922be55d-a0de-4a02-958a-14208c7c3b4f/%E6%8E%A5%E5%85%A5%E6%97%B6%E5%8F%91%E7%8E%B0%E7%9A%84%E9%97%AE%E9%A2%98.docx?Expires=1733745307&OSSAccessKeyId=LTAI4G23YViiKnxTC28ygQzF&Signature=bNvMjCd%2BDdjGX4BqBRuAK4tbHo4%3D",
        // "fileTotalPageCount":0,"pageWidth":null,"pageHeight":null}}
        if (ObjectUtils.isEmpty(eqbTemplateVo)) {
            throw new RuntimeException("文件上传失败");
        }
        ContractTemplate contractTemplate = new ContractTemplate();
        contractTemplate.setTemplateType(templateType);
        contractTemplate.setName(name);
        contractTemplate.setType(type);
        contractTemplate.setEnable("1");
        contractTemplate.setMerchantId(companyId);
        contractTemplate.setCreateUser(sysUser.getUserId());
        contractTemplate.setFile(FileUtil.subFileName(fileNamw));
        contractTemplate.setPdfUrl(eqbTemplateVo.getFileDownloadUrl());
        contractTemplate.setTemplateId(eqbTemplateVo.getDocTemplateId());
        contractTemplate.setTemplateCreateUrl(eqbTemplateVo.getDocTemplateCreateUrl());
        contractTemplate.setFileId(eqbTemplateVo.getFileId());
        return this.save(contractTemplate);
    }

    @Override
    public Boolean deleteById(Long id) {
        ContractTemplate template = this.getById(id);
        if (ObjectUtils.isEmpty(template)) {
            throw new RuntimeException("模板数据为空！");
        }
        if (StringUtils.isNotEmpty(template.getTemplateId())) {
            remoteToolService.deleteContract(template.getTemplateId());
        }
        return this.removeById(id);
    }

    /**
     * 根据类型查询合同模板
     * @param projectType
     * @return
     */
    @Override
    public ContractTemplate getType(Integer projectType) {
        return this.getOne(Wrappers.<ContractTemplate>lambdaQuery().eq(ContractTemplate::getType,projectType));
    }


}
